<?php
/**
 * @Author: rocky
 * @Copyright: 广州拓冠科技 <http://my8m.com>
 * Date: 2019/7/17
 * Time: 9:35
 */


namespace app\common\model;

//账单表
use think\Db;

class Account extends BaseModel
{
    protected $table = 'account_log';
    /**
     * 用户操作金额账单记录
     * @param float $money 金额
     * @param int $uid 用户id
     * @param string $title 账单标题
     * @param int $type 1用户支出，2用户收入
     * @param string $desc
     * @param int $store_id 门店id
     * @param int $order_id 订单id
     * @return bool
     */
    public static function recordMoney($money,$uid,$title,$type=1,$desc='',$store_id,$order_id){
        return self::record($money,$uid,$title,$type,true,$desc,$store_id,$order_id);
    }
    /**
     * 用户账单记录
     * @param float $money 金额
     * @param int $uid 用户id
     * @param string $title 账单标题
     * @param int $type 1用户支出，2用户收入
     * @param bool $wallet 是否操作钱包增减
     * @param string $desc
     * @param int $store_id 门店id
     * @param int $order_id 订单id
     * @return bool
     */
    public static function record($money,$uid,$title,$type=1,$wallet=false,$desc='',$store_id,$order_id){
        Db::startTrans();
        try {
            //记录账单
            self::create([
                'uid' => $uid,
                'title' => $title,
                'desc' => $desc,
                'money' => $money,
                'type' => $type,
                'store_id' => $store_id,
                'order_id' => $order_id
            ]);
            if($wallet){
                //用户余额增减操作
                if($type == 1){
                    User::where('id',$uid)->setDec('money',$money);
                }else{
                    User::where('id',$uid)->setInc('money',$money);
                }
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }

    public function store(){
        return $this->belongsTo(ShopStore::class,'store_id','id');
    }
    
    public function user(){
        return $this->belongsTo(User::class,'uid','id');
    }

    public function order(){
        return $this->belongsTo(ShopOrder::class,'order_id','id');
    }


    public function member(){
        return $this->hasMany(ShopMember::class,'uid','uid');
    }

    public function memberExpire(){
        return $this->hasMany(ShopMemberExpire::class,'order_id','order_id');
    }
}